import os, imp
import plugins.foolish
import gobject


class CodeBase(object):

    EDITOR = plugins.foolish.FoolishEditor()
    EDITOR_ARGS = []
    ROOT = os.getcwd()
    TMPDIR = os.path.join(ROOT, "tmp")

    components = { }


class NullComponent(object):
    def selected(self, *args):
        pass


class EditSession(gobject.GObject):
    pass

gobject.type_register(EditSession)
gobject.signal_new("edited", EditSession, 0, None, ())


def relativeToFullPath(relative_path):
    return os.path.join(CodeBase.ROOT, relative_path)

def fullToRelativePath(full_path):
    full_path = full_path.replace("\\", "/")
    if full_path.startswith(CodeBase.ROOT.replace("\\", "/") + "/"):
        return full_path[len(CodeBase.ROOT)+1:]
    else:
        return full_path

def editComponent(block_element, session=None):
    if hasattr(block_element, "code"):
        filename = relativeToFullPath(block_element.code)
    else:
        import tempfile
        filename = tempfile.mktemp(dir = CodeBase.TMPDIR, suffix = ".py")
        block_element.code = fullToRelativePath(filename)
    #args = CodeBase.EDITOR_ARGS + [filename]
    #os.spawnl(os.P_WAIT, CodeBase.EDITOR, CodeBase.EDITOR, *args)
    CodeBase.EDITOR.edit(filename, session)

def reloadComponent(block_element):
    import os.path
    bye(block_element)
    if hasattr(block_element, 'code'):
        filename = relativeToFullPath(block_element.code)
        if os.path.isfile(filename):
            J = imp.load_source("J", filename)
            j = CodeBase.components[id(block_element)] = J.entry()

def getComponent(block_element):
    try:
        return CodeBase.components[id(block_element)]
    except KeyError:
        return NullComponent()

def bye(block_element):
    try:
        del CodeBase.components[id(block_element)]
    except KeyError:
        pass
